package com.example.demo.utils

import java.util.*

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.interfaces.Claim
import java.util.*
/**
 * Jwt 工具类
 *
 * @author Raindrop
 */
open class JwtUtil {
    companion object {
        /* 秘钥 */
        private const val secret = "raindrop-666"
        /* 过期时间 15 分钟 */
        private const val expireTime = 15 * 60 * 1000
        /**
         * 生成 Token
         *
         * @param username 用户名
         * @return token 令牌
         */
        fun sign(username: String): String {
            val createDate = Date()
            val expireDate = Date(System.currentTimeMillis() + expireTime)
            val claims = mapOf("username" to username)
            return JWT.create()
                    .withHeader(claims)
                    .withSubject(username)
                    .withIssuedAt(createDate)
                    .withExpiresAt(expireDate)
                    .sign(Algorithm.HMAC512(secret))
        }
        /**
         * 解析 Token
         *
         * @param token 令牌
         * @return claim
         */
        fun parse(token: String): MutableMap<String, Claim>? {return JWT.decode(token).claims
        }
        /**
         * 检验 Token
         *
         * @param token 令牌
         * @return 有效 true 无效 false
         */
        fun verifyToken(token: String): Boolean {
            return try {JWT.require(Algorithm.HMAC512(secret)).build().verify(token)
                true
            } catch (e: Exception) {false}
        }
        /**
         * 获取用户名
         *
         * @param token 令牌
         * @return 用户名
         */
        fun getUserName(token: String) = JWT.decode(token).getClaim("username").asString()
        /**
         * 刷新 token
         *
         * @param token 原 token
         * @return 新 token
         */
        fun refresh(token: String): String {
            val createDate = Date()
            val expireDate = Date(System.currentTimeMillis() + expireTime)
            val username = parse(token)!!["sub"]?.asString()
            val header = mapOf("username" to username)
            return JWT.create()
                    .withHeader(header)
                    .withSubject(username)
                    .withIssuedAt(createDate)
                    .withExpiresAt(expireDate)
                    .sign(Algorithm.HMAC512(secret))
        }
    }
}